/* 
 * Copyright (c) 2012, Fromentin Xavier, Schnell Michaël, Dervin Cyrielle, Brabant Quentin
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *      * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *      * The names of its contributors may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Fromentin Xavier, Schnell Michaël, Dervin Cyrielle OR Brabant Quentin 
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package kameleon.gui.language ;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import kameleon.exception.KameleonException;
import kameleon.gui.exception.InvalidLanguageException;
import kameleon.gui.exception.UnknownKeyException;
import kameleon.gui.util.FileConstants;
import kameleon.gui.util.LanguageConstants;

/**
 * Utility class used to load the text parts from the language files.
 * 
 * @author		Schnell Michaël
 * @version		1.0
 */
public class SwitchLanguage implements FileConstants {

	/**
	 * Default language (English) used by the graphical interface.
	 */
	private static final GuiLanguage DEFAULT_LANGUAGE = 
			GuiLanguage.ENGLISH ;
	
	/**
	 * Text value used to return the given text.
	 */
	private static final String IDENTITY = "%s" ; //$NON-NLS-1$

	/**
	 * Only instance of this class.
	 */
	private static SwitchLanguage instance ;

	/**
	 * Base name of the language file.
	 */
	protected String languageFileName ;

	/**
	 * Current bundle.
	 */
	protected ResourceBundle bundle ;

	/**
	 * {@code ClassLoader} used to load the bundles.
	 */
	protected ClassLoader loader ;

	/**
	 * Current display language.
	 */
	protected GuiLanguage currentLanguage ;

	/**
	 * Builds an instance with the given language file name and
	 * {@code ClassLoader} using the default language.
	 * 
	 * @param	languageFileName
	 * 			base name of the language files
	 * 
	 * @param	loader
	 * 			{@code ClassLoader} used to load the resource bundles
	 */
	protected SwitchLanguage(String languageFileName, ClassLoader loader) {
		this.languageFileName = languageFileName ;
		this.currentLanguage = DEFAULT_LANGUAGE ;
		ResourceBundle.clearCache() ;
		this.loader = loader ;
		this.bundle = ResourceBundle.getBundle(
				languageFileName, 
				this.currentLanguage.getLanguage(), 
				this.loader) ;
	}// SwitchLanguage(String, ClassLoader)

	/**
	 * Returns the sole instance of this class.
	 * 
	 * @return	Sole instance of this class
	 */
	public static SwitchLanguage getInstance() {
		return instance ;
	}// getInstance()

	/**
	 * Initializes the sole instance of this class.
	 * 
	 * @throws 	KameleonException
	 * 			if an error occurred while initializing
	 */
	public static void initialize() throws KameleonException {
		try {
			URL[] urls = new URL[]{
					new File(LANGUAGE_FOLDER).toURI().toURL()} ;
			instance = new SwitchLanguage(LANGUAGE_FILE_NAME, 
					new URLClassLoader(urls)) ;
		} catch (MalformedURLException e) {
			//TODO Add exception ?
			throw new KameleonException(
					"Error while initializing SwitchLanguage", //$NON-NLS-1$
					e) ;
		}// try
	}// initialize()

	/**
	 * Returns the text part in the current language for the given key.
	 * {@link LanguageConstants} contains the list of valid keys for
	 * the language files.
	 * 
	 * @param 	key
	 * 			key of the requested text part
	 * 
	 * @return	text part in the given language associated with the given
	 * 			key
	 * 
	 * @throws 	UnknownKeyException
	 * 			if the given key was not found in the current language
	 * 			file
	 */
	public synchronized String getText(String key) 
			throws UnknownKeyException {
		if (key == null) {
			return IDENTITY ;
		}// if
		if (this.bundle.containsKey(key)) {
			return this.bundle.getString(key) ;
		}// if
		throw new UnknownKeyException(key, this.currentLanguage) ;
	}// getText(String)

	/**
	 * Returns the text part in the current language for the given key
	 * and formats it using the given arguments.
	 * This is a convenience function for the call <pre>
	 * String.format(this.getText(key), args) ;
	 * </pre>
	 * 
	 * @param 	key
	 * 			key of the requested text part
	 * 
	 * @param	args
	 * 			arguments used to format the requested text
	 * 
	 * @return	text part in the given language associated with the given
	 * 			key
	 * 
	 * @throws 	UnknownKeyException
	 * 			if the given key was not found in the current language
	 * 			file
	 * 
	 * @see		String#format(String, Object...)
	 */
	public synchronized String getText(String key, Object... args) 
			throws UnknownKeyException {
		return String.format(this.getText(key), args) ;
	}// getText(String, Object...)

	/**
	 * Returns the current language.
	 * 
	 * @return	Current language
	 * 
	 * @see		GuiLanguage
	 */
	public GuiLanguage getCurrentLanguage() {
		return this.currentLanguage ;
	}// getCurrentLanguage()

	/**
	 * Sets the display language.
	 * 
	 * @param 	lang
	 * 			new display language
	 * 
	 * @throws	InvalidLanguageException 
	 *			if no language file exists for the requested language
	 */
	public void changeLang(GuiLanguage lang) 
			throws InvalidLanguageException {
		GuiLanguage previousLang = this.currentLanguage ;
		this.currentLanguage = lang ;
		ResourceBundle.clearCache() ;
		ResourceBundle tmpBundle = null ;
		try {
			tmpBundle = ResourceBundle.getBundle(
					this.languageFileName, 
					this.currentLanguage.getLanguage(), 
					this.loader) ;
			this.bundle = tmpBundle ;
		} catch(MissingResourceException mre) {
			this.currentLanguage = previousLang ;
			throw new InvalidLanguageException(lang, mre) ;
		}// try
	}// changeLang(GuiLanguage)

}// class SwitchLanguage